<template>
    <div class="page-cont page-cont-ql" v-loading="loading">
        <h-section title="业务需求">
            <template #titleExtra>
                <div style="margin-left: 12px">
                    <a-dropdown :trigger="['click']">
                        <div class="ant-dropdown-link" @click.prevent>
                            标准模板
                            <HIcon icon="DownOutlined" />
                        </div>
                    </a-dropdown>
                </div>
            </template>
            <div>
                <a-form layout="inline" ref="ruleFormRef" :model="form" :rules="rules">
                    <a-row :gutter="24">
                        <a-col :span="24">
                            <a-form-item label="需求标题" name="requestName">
                                <span style="white-space: pre-wrap" v-html="form.requestName" v-if="disabled" />
                                <a-textarea
                                    v-model:value="form.requestName"
                                    placeholder="请输入需求标题限制200个字"
                                    :maxlength="200"
                                    auto-size
                                    v-else
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="24">
                            <a-form-item label="是否系统性分析">
                                <span v-if="disabled">{{ form.isRequireAnalyse }}</span>
                                <a-radio-group v-model:value="form.isRequireAnalyse" v-else>
                                    <a-radio value="是">是</a-radio>
                                    <a-radio value="否">否</a-radio>
                                </a-radio-group>
                                <span class="caption-font-color margin-l-8">提示：不确定属于哪个系统或需要拆分到多系统完成的需求，请选择是；</span>
                            </a-form-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-item label="需求类型" name="requestType">
                                <div style="width: 100%">
                                    <span v-if="disabled">
                                        {{ $filters.valToNameFilter('requestType', form.requestType) }}
                                    </span>
                                    <a-select placeholder="请选择" v-model:value="form.requestType" v-else>
                                        <a-select-option v-for="item of dicOptions.requestType" :key="item.code">
                                            {{ item.dimensionName }}
                                        </a-select-option>
                                    </a-select>
                                </div>
                            </a-form-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-item label="所属产品" name="requestSystem">
                                <div style="width: 100%">
                                    <span v-if="disabled">
                                        {{ $filters.valToNameFilter('fromSystem', form.requestSystem) }}
                                    </span>
                                    <HSearchSelectCell
                                        allowClear
                                        :default-value="$filters.valToNameFilter('fromSystem', form.requestSystem)"
                                        type="allSystem"
                                        label="system"
                                        @success="handleSelectChange($event, 'requestSystem')"
                                        v-else
                                    />
                                </div>
                            </a-form-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-item label="负责人" name="agentUserName">
                                <div style="width: 100%">
                                    <span v-if="disabled">{{ form.agentUserName }}</span>
                                    <HSearchSelectCell
                                        :disabled="form.isRequireAnalyse === '是' || !form.requestSystem"
                                        :default-value="form.agentUserName"
                                        type="systemManager"
                                        label="empName"
                                        :searchQuery="{ catalogCode: form.catalogCode }"
                                        @success="handleSelectChange($event, 'agentUserName')"
                                        v-else
                                    >
                                        <template #label="{ record }"> {{ record.empName }}（{{ record.empId }}） </template>
                                    </HSearchSelectCell>
                                </div>
                            </a-form-item>
                        </a-col>
                        <a-col :span="8" v-if="detail.id">
                            <a-form-item label="来源" name="source">
                                <div style="width: 100%">
                                    <span>{{ $filters.valToNameFilter('source', form.source) }}</span>
                                </div>
                            </a-form-item>
                        </a-col>

                        <!-- 可以替别人发起，但是如果发起人不在系统配置的人员中（可以进系统管理查看人员配置情况）则如果驳回，还是会驳回到创建人手中 -->
                        <a-col :span="8">
                            <a-form-item label="发起人" name="initiator">
                                <span v-if="disabled">
                                    {{ form.initiator }}
                                </span>
                                <flexbox v-else>
                                    <flexbox-item>
                                        <HSearchSelectCell
                                            :default-value="{ empId: form.initiatorEmpId, empName: form.initiator }"
                                            valueLabelField="empName"
                                            keyField="empId"
                                            type="allUser"
                                            @success="handleSelectChange($event, 'initiator')"
                                        >
                                            <template #label="{ record }"> {{ record.name }}（{{ record.empId }}） </template>
                                        </HSearchSelectCell>
                                    </flexbox-item>
                                    <div class="margin-l-8 warning-color cursor-pointer" @click="handleSendByMy">本人发起</div>
                                </flexbox>
                            </a-form-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-item label="所属部门">
                                <span>{{ form.initiatorDept }}</span>
                            </a-form-item>
                        </a-col>
                        <a-col :span="16">
                            <a-form-item label="需求描述" name="requestDesc">
                                <div style="position: relative">
                                    <div v-html="form.requestDesc" v-if="disabled" class="desc-content" />
                                    <t-editor ref="editor" v-model="form.requestDesc" v-else />
                                </div>
                            </a-form-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-item label="标签">
                                <div v-if="disabled">
                                    <flexbox wrap="wrap" v-if="form.pmpLabels">
                                        <a-tag color="blue" style="margin-bottom: 2px" v-for="item of form.pmpLabels" :key="item.id">
                                            {{ item.name }}
                                        </a-tag>
                                    </flexbox>
                                </div>
                                <HSearchMultiSelectCell
                                    :defaultValue="form.pmpLabels"
                                    type="systemLabel"
                                    label="name"
                                    valueLabelField="name"
                                    keyField="name"
                                    isSupportEnter
                                    :disabled="!form.requestSystem"
                                    :searchQuery="{ systemId: form.requestSystem, type: 2 }"
                                    @success="handleSelectChange($event, 'label')"
                                    v-else
                                />
                            </a-form-item>
                            <a-form-item label="期望完成日期">
                                <div style="width: 100%">
                                    <span v-if="disabled">{{ $filters.dateFilter(form.expectTime) }}</span>
                                    <h-date-picker-cell v-model:value="form.expectTime" v-else />
                                </div>
                            </a-form-item>
                            <a-form-item label="优先级">
                                <div v-if="disabled">
                                    <h-level :level="form.level" v-if="form.level" />
                                </div>
                                <a-select placeholder="请选择" v-model:value="form.level" style="text-align: left" v-else>
                                    <a-select-option v-for="item of dicOptions.level" :key="item.code">
                                        {{ item.dimensionName }}
                                    </a-select-option>
                                </a-select>
                            </a-form-item>

                            <a-form-item label="rat需求编号">
                                <span>{{ form.ratNumber }}</span>
                            </a-form-item>

                            <a-form-item label="文档">
                                <file-cell v-if="disabled" :fileList="form.selfRequestFiles || []" />
                                <upload-cell
                                    :span="24"
                                    :fileParams="{ connectType: modelName, type: 0 }"
                                    @valueChange="fileChange"
                                    :fileList="form.selfRequestFiles || []"
                                    v-else
                                >
                                    <template #extra>
                                        <span class="caption-font-color">提示：您可以上传工作沟通记录截图作为需求发起的依据</span>
                                    </template>
                                </upload-cell>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
        </h-section>
        <task-record v-bind="$props" v-if="detail.id && !disabled" />
    </div>

    <!-- 添加固定底部按钮 -->
    <div class="create-task-form-buttons" v-if="!disabled">
        <!-- 驳回的需求可以删除 -->
        <a-button type="primary" danger @click="handleDelete" v-if="canDelete">删除</a-button>
        <a-button type="primary" danger @click="handleUpdate" v-if="canDelete">废弃</a-button>
        <!-- 驳回的需求不能保存为草稿 -->
        <a-button @click="handleSubmit('4')" v-if="!detail.instanceId">存为草稿</a-button>
        <a-button type="primary" @click="handleSubmit('1')">发起需求</a-button>
    </div>
</template>

<script lang="ts">
import { message } from 'ant-design-vue';
import { UploadCell, FileCell, HLevel, HSearchSelectCell, HDatePickerCell, HSearchMultiSelectCell } from '@/components';
import TaskRecord from '@/views/taskRequire/taskDetail/components/HistoryRecord/task/index.vue';
import { useMessage } from '@/hooks/common/useMessage';
import { useRouter, useRoute, onBeforeRouteLeave } from 'vue-router';
import { useTaskFormData, useCreateTaskForm } from '@/views/taskRequire/createTaskRequire/hooks';
import store from '@/store';
import api from '@/api';
import { computed, defineComponent, ref, unref, watch, defineAsyncComponent, nextTick } from 'vue';
export default defineComponent({
    name: 'CreateRequire',
    components: {
        UploadCell,
        FileCell,
        HLevel,
        HSearchSelectCell,
        HDatePickerCell,
        HSearchMultiSelectCell,
        TaskRecord,
        TEditor: defineAsyncComponent(() => import('@/components/TEditor/index.vue'))
    },
    props: {
        detail: { type: Object, default: () => ({}) }
    },
    setup(props) {
        const router = useRouter();
        const route = useRoute();
        const { form, setForm } = useTaskFormData();
        const { beforeSubmit, handleSendByMy, handleSelectChange, fileChange } = useCreateTaskForm(setForm);
        const ruleFormRef = ref<any>();
        const oldDesc = ref<any>('');
        const loading = ref<boolean>(false);
        const modelName = '发起需求';
        //废弃状态显示为不可编辑
        const disabled = computed(() => {
            if (props.detail.id) {
                if (props.detail.status === '4') {
                    if (store.getters.userInfo.employeeDTO.empId !== props.detail.createUserEmpId) {
                        return true;
                    }
                    return false;
                } else if (props.detail.status === '5') {
                    return true;
                } else {
                    if (store.getters.userInfo.employeeDTO.empId !== props.detail.agentUser) {
                        return true;
                    }
                    return false;
                }
            }
            return false;
        });
        const rules = computed(() => {
            const rules = {
                requestName: [{ required: true, message: '需求标题不能为空', trigger: 'blur' }],
                requestType: [{ required: true, message: '需求类型不能为空', trigger: 'blur' }],
                requestSystem: [{ required: true, message: '所属产品不能为空', trigger: 'blur' }],
                initiator: [{ required: true, message: '发起人不能为空', trigger: 'change' }],
                requestDesc: [{ required: true, message: '需求描述不能为空', trigger: 'blur' }],
                agentUserName: form.value.isRequireAnalyse === '否' ? [{ required: true, message: '负责人不能为空', trigger: 'blur' }] : []
            };
            return unref(disabled) ? {} : rules;
        });
        const canDelete = computed(() => {
            const { status } = props.detail;
            return status === '8';
        });
        const handleSubmit = (status: string) => {
            unref(ruleFormRef)
                .validate()
                .then(() => {
                    setForm({
                        status
                    });
                    if (status === '1') {
                        beforeSubmit(handleSave);
                    } else {
                        handleSave();
                    }
                })
                .catch(() => {
                    // 验证失败时滚动到第一个错误字段
                    nextTick(() => {
                        const errorField = document.querySelector('.ant-form-item-has-error');
                        if (errorField) {
                            errorField.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        }
                    });
                });
        };
        // 删除
        const handleDelete = () => {
            const { createConfirm } = useMessage();
            createConfirm({
                title: '确认删除当前数据？',
                iconType: 'danger',
                onOk: async () => {
                    const query = {
                        id: props.detail.id
                    };
                    const { success, errorMsg } = await api.pmpRequestInfoModel.delete(query);
                    if (success) {
                        oldDesc.value = form.value.requestDesc;
                        message.success('删除成功');
                        router.push({
                            path: '/taskRequire/myRequire'
                        });
                    } else {
                        message.error(errorMsg);
                    }
                }
            });
        };
        const handleUpdate = async () => {
            const query = {
                id: props.detail.id,
                status: 5
            };
            const { success, errorMsg } = await api.pmpRequestInfoModel.updateBusiness(query);
            if (success) {
                message.success('操作成功');
                oldDesc.value = form.value.requestDesc;
                router.push({
                    path: '/taskRequire/myRequire'
                });
            } else {
                message.error(errorMsg);
            }
        };
        // 获取系统信息
        const getSystemInfo = async (id) => {
            const { success, moule } = await api.productDetailModel.findById({
                id
            });
            if (success) {
                setForm({
                    pmpLabels: [],
                    catalogCode: moule.catalogCode
                });
            }
        };
        const handleSave = async (showMsg = true) => {
            loading.value = true;
            let query: any = {
                ...unref(form),
                createUser: store.getters.userInfo.employeeDTO.name
            };
            // 选择系统分析之后，清空已选择的负责人信息
            if (query.isRequireAnalyse === '是') {
                query = {
                    agentUser: null,
                    agentUserName: null,
                    ...query
                };
            }
            const { success, errorMsg } = await api.pmpRequestInfoModel.save(query);
            if (success) {
                oldDesc.value = form.value.requestDesc;
                if (showMsg) {
                    message.success(unref(form).id ? '操作成功' : '创建成功');
                    if (unref(form).id) {
                        router.push({
                            path: '/taskRequire/myRequire'
                        });
                    } else {
                        router.push({
                            path: '/workbench'
                        });
                    }
                }
            } else {
                message.error(errorMsg);
            }
            loading.value = false;

            return { success, errorMsg };
        };
        watch(
            () => form.value.requestSystem,
            () => {
                setForm({
                    agentUserName: null,
                    agentUser: null
                });
            },
            { deep: true }
        );
        const init = () => {
            if (props.detail.id) {
                Object.keys(unref(form)).forEach((key) => {
                    if (key === 'selfRequestFiles') {
                        if (props.detail.selfRequestFiles) {
                            setForm({
                                selfRequestFiles: props.detail.selfRequestFiles.filter((item) => item.connectType === modelName)
                            });
                        }
                    } else {
                        if (key === 'catalogCode') {
                            setForm({
                                [key]: props.detail.pmpProductDetailDTO.catalogCode
                            });
                        } else {
                            setForm({
                                [key]: props.detail[key]
                            });
                        }
                    }
                });
                setForm({
                    agentUserName: null,
                    agentUser: null
                });
                oldDesc.value = form.value.requestDesc;
            } else {
                // 路径跳转过来的系统id
                const systemId: any = route.query.systemId || null;
                form.value.requestSystem = systemId;
                if (form.value.requestSystem) {
                    getSystemInfo(form.value.requestSystem);
                }
            }
        };
        init();
        onBeforeRouteLeave((to, from, next) => {
            if (oldDesc.value !== form.value.requestDesc) {
                const { createConfirm } = useMessage();
                createConfirm({
                    title: `编辑内容尚未保存，是否保存？`,
                    iconType: 'danger',
                    onOk: async () => {
                        unref(ruleFormRef)
                            .validate()
                            .then(async () => {
                                setForm({
                                    status: '4'
                                });
                                const res: any = await handleSave(false);
                                if (res.success) {
                                    message.success('保存成功');
                                    next();
                                } else {
                                    message.error(res.errorMsg);
                                }
                            });
                    },
                    onCancel: () => {
                        next();
                    }
                });
            } else {
                next();
            }
        });
        return {
            ruleFormRef,
            loading,
            oldDesc,
            modelName,
            rules,
            form,
            disabled,
            canDelete,
            handleSubmit,
            handleDelete,
            handleUpdate,
            fileChange,
            handleSendByMy,
            handleSelectChange
        };
    }
});
</script>
<style lang="less">
.page-cont-ql {
    .ql-snow .ql-picker {
        line-height: 20px !important;
    }
}
</style>
<style scoped lang="less">
.page-cont {
    min-height: 516px;
    margin-top: 22px;
    background: #fff;
    padding-bottom: 32px; // 为固定按钮腾出空间
}

.create-task-form-buttons {
    position: fixed;
    bottom: 24px;
    right: 66px;
    z-index: 1000;
    display: flex;
    gap: 8px;
}
</style>
